from waveapi import events,model,robot,document
from urllib import quote
import re


Regexp=re.compile('\$\$(.+?)\$\$',re.MULTILINE|re.DOTALL)
Regexp1=re.compile('\=\=(.+?)\=\=',re.MULTILINE|re.DOTALL)
WelcomeText='''
Hi, i am the latex robot.
Example:

input: \mbox{\LaTeX} (surrounded by 2 $\'s)
result: $\mbox{\LaTeX}$
To change back from pictures to text, surround the images in 2 ='s on each side.
'''
#LatexImg="""http://sciencesoft.at/image/latexurl/?template=ams&dev=jpeggray&dpi=120&src=%s"""
LatexImg="http://www.codecogs.com/gif.latex?%s"

def GetAnnotations(self, name=None, range=None):
	"""Get named annotations of this document.
	Args:
	name: optional key name of the annotation.
	Returns:
	Array of annotations [{'name':annotation_name,
	'value:annotation_value, 'range':(annotation_range_start,
	annotation_range_end)}]
	"""
	annotations = []
	for a in self._blip.annotations:
		if range and range.end < a.range.start or a.range.end < range.start: continue
		elif not name or a.name == name: annotations.append(document.Annotation(a.name,a.value,a.range))
	return annotations 


def OnRobotAdded(properties, context):
	"""Invoked when the robot has been added."""
	root_wavelet = context.GetRootWavelet()
	root_wavelet.CreateBlip().GetDocument().SetText(WelcomeText)

def OnChange(prop,context):
	blip=context.GetBlipById(prop['blipId']).GetDocument()
	txt=blip.GetText()
	latex=Regexp.finditer(txt)
	unlatex=Regexp1.finditer(txt)
	for m in latex:
		cod=m.group(1)
		#blip.InsertText(m.end(),"LaTeX")
		im=document.Image(url=LatexImg%quote(cod.replace('\n', ''),''),caption=cod)
		blip.InsertText(m.end(),' ')
		blip.DeleteRange(document.Range(*m.span()))
		blip.InsertElement(m.start(),im)
		blip.SetAnnotation(document.Range(m.start(),m.start()+1), "tex" ,'$'+cod+'$' )
		#blip.SetAnnotation(document.Range(m.start(),m.start()+1), "style/backgroundColor", "rgb(255, 0, 0)" )
	for n in unlatex:
		#Remove the 's
		blip.DeleteRange(document.Range(n.end()-2, n.end()))
		blip.DeleteRange(document.Range(n.start(), n.start()+2))
		outs = GetAnnotations(blip, 'tex', document.Range(n.start(),n.end()))
		#outs = blip.GetAnnotations('style/backgroundColor', document.Range(n.start(),n.start()))
		for x in reversed(outs):
			myvalue=x.value
			myname=x.name
			#blip.DeleteElement(x.range.start)
			blip.InsertText(x.range.end-1, myvalue + ' ')
	
if __name__ == '__main__':
  myRobot = robot.Robot('la-texy', 
      image_url='http://la-texy.appspot.com/latex.png',
      version='1',
      profile_url='http://la-texy.appspot.com/')
  myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
  myRobot.RegisterHandler(events.DOCUMENT_CHANGED, OnChange)
  myRobot.Run()
